<?php

namespace app\command;

use app\common\mqtt\MqttService;
use PhpMqtt\Client\Exceptions\MqttClientException;
use think\console\Command;
use think\console\Input;
use think\console\Output;

class MqttSubscribe extends Command
{
    protected function configure()
    {
        $this->setName('mqtt:subscribe')
            ->setDescription('MQTT 订阅并监听消息（常驻进程，Ctrl+C 退出）');
    }

    protected function execute(Input $input, Output $output)
    {
        $service = new MqttService();
        $topics = config('mqtt.topics') ?: ['demo/topic' => 0];

        try {
            $output->writeln('[MQTT] 正在连接...');
            $service->connect();

            $output->writeln('[MQTT] 订阅主题：' . json_encode($topics, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
            $service->subscribe($topics, function (string $topic, string $message, bool $retained) use ($output) {
                $output->writeln(sprintf('[%s] topic=%s retained=%s message=%s',
                    date('Y-m-d H:i:s'),
                    $topic,
                    $retained ? 'true' : 'false',
                    $message
                ));
            });

            $output->writeln('[MQTT] 开始监听，按 Ctrl+C 退出');
            $service->loopForever();
        } catch (MqttClientException $e) {
            $output->writeln('[MQTT] 异常：' . $e->getMessage());
            return self::FAILURE;
        }

        return self::SUCCESS;
    }
}


